package com.zoffy.oj_backend.aop;

import com.zoffy.oj_backend.annotation.AuthCheck;
import com.zoffy.oj_backend.common.ErrorCode;
import com.zoffy.oj_backend.exception.BusinessException;
import com.zoffy.oj_backend.model.enums.UserRole;
import com.zoffy.oj_backend.model.vo.UserVo;
import com.zoffy.oj_backend.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Component
@Aspect
public class AuthInterceptor {
    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        UserRole mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        UserVo loginUser = userService.currentUserVo(request);

        //如果不需要登陆则直接放行
        if (UserRole.NOT_LOGIN.equals(mustRole)) {
            return joinPoint.proceed();
        }
        //若用户未登陆该方法将抛出错误而阻止请求
        String userRole = loginUser.getUserRole();
        if (UserRole.ADMIN.equals(mustRole)) {
            if (!UserRole.ADMIN.getName().equals(userRole)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "权限不足");
            }
        }
        return joinPoint.proceed();

    }
}
